require 'active_support'

## 
# host param for tunnel is sorta useless, in vmware scenario because
# it only binds to the 

## this should move into a method and be a dependecy of the tasks
@file = '.palm'
@remote = 'remote-app'
if File::exists?(@file)
	@dir = Dir.getwd + "/" + IO.readlines(@file,'')[0].strip
	File.open("#{@dir}/appinfo.json") do |f|
		@json = ActiveSupport::JSON.decode(f.read)
	end
end

def ipk
	"#{@json['id']}_#{@json['version']}_all.ipk"
end

desc "Default task, listing what we can do"
task :default do
	puts "Listing tasks"
	puts "All arguments have reasonable defaults"
	puts "Arguments have to specified in rake task[arg] syntax"
	puts "Maybe we find another way than just executing rake -T .."
	puts "" 
	sh "rake -T"
end

desc "Generate a new palm app"
task :generate, :name do |t,args|
	args.with_defaults(:name => 'new_app')
	sh "palm-generate -t new_app #{args[:name]}"
	sh "echo #{args[:name]} > #{@file}"
end

desc "setup ssh tunnel to the emulator for http access, host is single iface port is bound to"
task :tunnel, :host do |t,args|
	args.with_defaults(:host => 'localhost')
	sh "ssh -p 5522 -L 5581:localhost:8080 root@#{args[:host]}"
end

desc "mount the app to local directory"
task :mount, :host do |t,args|
	args.with_defaults(:host => 'localhost')
	remote = 'remote-app'
	sh "mkdir #{@remote}" unless File.directory?(remote)
	path = "/media/cryptofs/apps/usr/palm/applications/#{@json['id']}"
	sh "sshfs -p 5522 root@#{args[:host]}:#{path} #{@remote}"
end

desc "umount the app to local directory"
task :umount do |t,args|
	sh "fusermount -u #{@remote}"
end

desc "Sync the local directory with the working directory"
task :rsync do
	sh "mkdir #{@remote}" unless File.directory? @remote
	sh "rsync -rva --exclude .svn  #{@dir}/* #{@remote}"
end

desc "Run the express app"
task :express do
	sh "node expressapp/app.js #{@dir}"
end

desc "Remove the app"
task :remove do
	sh "rm #{ipk}"
end
task :uninstall do
	sh "palm-install -r #{@json['id']}"
end

task :package do 
	sh "palm-package #{@dir}"
end

task :install do 
	sh "palm-install #{ipk}"
end

task :launch do 
	sh "palm-launch -i #{@json['id']}"
end
task :log do
	sh "palm-log -f #{@json['id']}"
end

task :run => [:package, :install, :launch, :log]
task :clear => [:remove, :uninstall]


